package cn.sytton.taffe.file.controller;

import cn.sytton.taffe.file.entity.FileEntity;
import cn.sytton.taffe.file.service.IFileService;
import cn.sytton.taffe.file.service.impl.FileTempService;
import cn.sytton.taffe.framework.exception.BizException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 公共文件服务控制层
 *
 * @author skyrock
 */
@Tag(name = "文件")
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private IFileService fileService;
    @Resource
    private FileTempService fileTempService;

    @Operation(summary = "下载文件")
    @Parameter(name = "fileId", description = "文件ID", in = ParameterIn.PATH, required = true)
    @GetMapping("/download/{fileId}")
    public void download(@PathVariable String fileId) {
        fileService.download(fileId);
    }

    @Operation(summary = "下载文件组,返回zip压缩包")
    @Parameters({
        @Parameter(name = "groupId", description = "文件组ID", in = ParameterIn.PATH, required = true),
        @Parameter(name = "name", description = "下载文件命名", in = ParameterIn.QUERY, required = true)
    })
    @GetMapping("/group/download/{groupId}")
    public void downloadGroup(@PathVariable String groupId, @RequestParam(value = "name", required = false) String name) {
        fileService.downloadGroup(groupId, name);
    }

    @Operation(summary = "上传临时文件")
    @PostMapping("/temp/upload")
    public FileEntity uploadTempFile(@RequestBody MultipartFile file) {
        FileEntity fileEntity = fileTempService.upload(file);
        if (fileEntity != null) {
            return fileEntity;
        } else {
            throw new BizException("上传失败");
        }
    }

    @Operation(summary = "下载临时文件")
    @Parameter(name = "objectName", description = "存储对象名", in = ParameterIn.QUERY, required = true)
    @GetMapping("/temp/object/download")
    public void downloadTempObject(String objectName) {
        fileTempService.downloadObject(objectName);
    }

    @Operation(summary = "获取文件访问路径")
    @Parameters({
        @Parameter(name = "fileId", description = "文件ID", in = ParameterIn.PATH, required = true),
        @Parameter(name = "public", description = "是否可永久访问", in = ParameterIn.QUERY, required = true)
    })
    @GetMapping("/{fileId}")
    public String getUrl(@PathVariable String fileId, @RequestParam(value = "public", required = false) Boolean isPublic) {
        if (isPublic == null || !isPublic) {
            return fileService.getUrl(fileId);
        } else {
            return fileService.getPublicUrl(fileId);
        }
    }
}
